import React, { useState } from "react";
import { Button, Upload, message, Popconfirm, Space } from "antd";
import { useTranslation } from 'react-i18next';
import { UploadOutlined, DeleteOutlined, StarOutlined } from '@ant-design/icons';
import { apiMSDModuleFileUpload, apiMSDModuleFileRemove } from '../../../services/masterData/module'
import DeleteConfirm from '../DeleteConfirm';
import _ from 'lodash';
import './index.scss';

const UploadItem = ({
  // 上传按钮文案
  btnText,
  // 附件类型
  acceptType,
  // 上传至哪个Module
  uploadModule,
  // 上传至哪个Module的具体记录
  uploadName,
  // 上传或删除更新
  uploadUpdateFn,
  // 是否disabled
  disabled,
  // fileList
  fileListData,
  // 最大上传数量
  maxCount,
}) => {
  const { t } = useTranslation();
  const [fileList, setFileList] = useState(fileListData || []);
  const { TYPE, VERIFIED } = acceptType;
  const acceptText = TYPE?.join(',');

  const beforeUpload = (file) => {
    return false;
  };
  const uploadChange = (file) => {
    if (file?.file?.status !== 'removed') {
      const type = file?.file?.type || file?.file?.name?.split('.')?.pop()?.toLowerCase();
      const isValidType = VERIFIED?.includes(type);
      console.log(isValidType);
      if (!isValidType && VERIFIED?.length !== 0) {
        message.error(t('common.uploadTips', { type: TYPE }));
        return false;
      };
      uploadFile(file);
    };
  };
  const uploadFile = (file) => {
    const targetUid = file.file.uid;
    const originFileObj = file.fileList.find(item => item.uid === targetUid)?.originFileObj;
    let param = new FormData();
    param.append('file', originFileObj);
    param.append('name', uploadName);
    param.append('type', uploadModule);
    apiMSDModuleFileUpload(param).then((res) => {
      if (res?.data) {
        const originFileList = maxCount === 1 ? [] : [...fileList];
        const newFileList = [
          ...originFileList,
          {
            name: res?.data?.data?.attachmentUrl,
            status: 'done',
            url: res?.data?.data?.attachmentUrl,
            attachmentUrl: res?.data?.data?.attachmentUrl,
          }
        ];
        setFileList(newFileList);
        uploadUpdateFn(newFileList);
      };
    });
  };
  const removeChange = (file) => {
    DeleteConfirm({
      t,
      title: t('common.deleteFileMsg'),
      onOk () {
        const params = {
          fileUrl: file.attachmentUrl,
          name: uploadName,
          type: uploadModule
        };
        apiMSDModuleFileRemove(params).then((res) => {
          if (res?.data) {
            const newFileList = [...fileList];
            _.remove(newFileList, (curr => curr.name === file.name));
            setFileList(newFileList);
            uploadUpdateFn(newFileList);
          };
        });
      }
    });
  };
  return (
    <Upload
      className='upload-item-wrap'
      maxCount={maxCount}
      disabled={disabled}
      accept={acceptText}
      beforeUpload={beforeUpload}
      onChange={(e) => uploadChange(e)}
      onRemove={(e) => removeChange(e)}
      fileList={fileList}
    >
      <Button disabled={disabled} icon={<UploadOutlined />} >{btnText}</Button>
    </Upload>
  )
};

export default UploadItem;